﻿using System;
using System.Text.RegularExpressions;

namespace DataStore.Domain
{
    /// <summary>
    /// A written work or composition that has been published.
    /// </summary>
    [Serializable]
    public class Book : CatalogItem
    {
        public Book() : base()
        {
            // Add fields for validation
            FieldsForValidation.Add("ISBN");
        }

        /// <summary>
        /// Gets or sets the ISBN number.
        /// </summary>
        /// <value>The ISBN-10.</value>
        public virtual string ISBN { get; set; }


        /// <summary>
        /// Gets the <see cref="System.String"/> with the specified column name.
        /// </summary>
        /// <value></value>
        public override string this[string columnName]
        {
            get
            {
                string error =  base[columnName];

                if(columnName == "ISBN")
                {
                    if(!string.IsNullOrEmpty(ISBN) && !IsISBNFormat(ISBN))
                    {
                        error = "ISBN not in proper format.";
                    }
                }

                return error;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ISBN"></param>
        /// <returns></returns>
        private bool IsISBNFormat(string ISBN)
        {
            Regex isbnFormat = new Regex(
                @"^(97(8|9))?\d{9}(\d|X)$",
                RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
            return isbnFormat.IsMatch(ISBN);
        }

        //private bool IsISBNChecksumCorrect(string ISBN)
        //{
        //    int length = ISBN.Trim().Length;
        //    if(length == 10)
        //    {
        //        char[] digits = ISBN.ToCharArray();
        //        int sum = 0;
        //        for (int i = 0; i<= 8; i++)
        //        {
        //            int digit = int.Parse(digits[i].ToString());
        //            sum += digit * (10-i);
        //        }
        //        int checkDigit = int.Parse(digits[9].ToString());

        //        int checksum = 11 - (sum%11);

        //        return checkDigit == checksum;
                

                
        //    }
        //    else if(length == 13)
        //    {
                
        //    }
        //    else
        //    {
        //        throw new ArgumentOutOfRangeException("ISBN must be 10 or 13 characters long");
        //    }
        //}
    }
}
